package com.kedou.net;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.kedou.app.Config;
import com.kedou.app.R;
import com.kedou.domain.Fund;
import com.kedou.domain.ProjectItem;
import com.kedou.net.PostGoFund.FailCallback;
import com.kedou.net.PostGoFund.SuccessCallback;
import com.kedou.util.Util;

/**
 * 后台请求：获取关注的项目列表
 * 
 * @author zhouchao
 * 
 */
public class PostFollowedProject {
	public PostFollowedProject(String token, String userId, String os,
			String deviceId, final SuccessCallback successCallback,
			final FailCallback failCallback, final Context context) {
		new NetConnection(
				Util.getSDBaseUrl() + Config.URL_GETFOLLOWEDPROJECT,
				HttpMethod.POST,
				new NetConnection.SuccessCallback() {

					@Override
					public void onSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							switch (obj.getInt(Config.KEY_STATUSCODE)) {
							case Config.RESULT_STATUS_SUCCESS:
								ArrayList<ProjectItem> mProjects = new ArrayList<ProjectItem>();
								JSONArray jsonArray = obj.getJSONArray("data");
								for (int i = 0; i < jsonArray.length(); i++) {
									ProjectItem item = new ProjectItem();
									JSONObject obj1 = (JSONObject) jsonArray
											.get(i);
									if (obj1.has("projectPic")) {
										item.setProjectSlogan(obj1
												.getString("projectPic"));
									}
									if (obj1.has("projectName")) {
										item.setProjectName(obj1
												.getString("projectName"));
									}
									if (obj1.has("projectId")) {
										item.setProjectId(obj1
												.getString("projectId"));
									}
									mProjects.add(item);
								}
								if (successCallback != null) {
									successCallback.onSuccess(
											obj.getString(Config.KEY_STATUSMSG),
											mProjects);
								}
								break;
							default:
								if (failCallback != null) {
									failCallback.onFail(obj
											.getString(Config.KEY_STATUSMSG));
								}
								break;
							}

						} catch (JSONException e) {
							e.printStackTrace();
							if (failCallback != null) {
								failCallback.onFail(context.getResources()
										.getString(R.string.server_have_wrong));
							}
						}
					}
				}, new NetConnection.FailCallback() {

					@Override
					public void onFail() {
						if (failCallback != null) {
							failCallback.onFail(context.getResources()
									.getString(R.string.server_have_wrong));
						}
					}
				}, Config.KEY_TOKEN, token, Config.KEY_USERID, userId,
				Config.KEY_OS, os, Config.KEY_DEVICE, deviceId);
	}

	public static interface SuccessCallback {
		void onSuccess(String msg, ArrayList<ProjectItem> projects);
	}

	public static interface FailCallback {
		void onFail(String msg);
	}
}
